<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>店铺信息</span>
      </div>
      <div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="门店账号" required>
              <el-input v-model.trim="ruleForm.userName" placeholder="请输入门店账号" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店名称" required>
              <el-input v-model.trim="ruleForm.storeName" placeholder="请输入门店名称" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店编码" required>
              <el-input v-model.trim="ruleForm.storeNo" placeholder="请输入门店编码" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺分类">
              <el-select filterable clearable v-model="ruleForm.storeType" placeholder="请选择店铺分类" :value-key="'label'" class="full-width">
                <el-option v-for="(item, index) in shopClass" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在地区" prop="provinceName">
              <div class="flex flex-start">
                <!-- 省 -->
                <el-select v-model="ruleForm.provinceName" placeholder="请选择省" clearable @change="provinceChange($event)" value-key="id">
                  <el-option v-for="(item, index) in provinceData" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                <!-- 市 -->
                <el-select v-model="ruleForm.cityName" placeholder="请选择市" clearable @change="cityNameChange($event)" value-key="id">
                  <el-option v-for="(item, index) in cityData" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                <!-- 区 -->
                <el-select v-model="ruleForm.districtName" placeholder="请选择区" clearable @change="districtChange($event)" value-key="id">
                  <el-option v-for="(item, index) in districtData" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                <!-- 街道 -->
                <el-select v-model="ruleForm.streetName" placeholder="选择街道" clearable @change="streetChange($event)" value-key="id">
                  <el-option v-for="(item, index) in streetData" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="ruleForm.address" placeholder="请输入详细地址" maxlength="100" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属商户" v-if="JSON.parse(this.$store.state.user.userInfo).userType != 0">
              <el-input v-model="MerchantId"></el-input>
            </el-form-item>
            <el-form-item label="所属商户" prop="mchId" class="phones" v-else>
              <el-select v-model="ruleForm.mchId" placeholder="请选择" clearable class="select" @change="selectMerchantId($event)" value-key="id">
                <el-option v-for="item in merchantName" :key="item.id" :label="item.mchName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店LOGO" prop="logoImage">
              <app-uploader title="门店LOGO" :limit="1" :initFiles="ruleForm.storeLogo" :accept="'image/*'" :file-format="fileFormat" @change="handleImagesOption($event, 'storeLogo')"></app-uploader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店实景图" prop="storeImage">
              <app-uploader title="门店实景图" :limit="1" :initFiles="ruleForm.storeImg" :accept="'image/*'" :file-format="fileFormat" @change="handleImagesOption($event, 'storeImg')"></app-uploader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定门店">
              <el-switch v-model="value1" @change="switchChange"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用线上店铺">
              <el-switch v-model="value2" @change="switchChange2"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="margin_top_20">
      <div slot="header" class="clearfix">
        <span>经营者信息</span>
      </div>
      <div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="门店负责人" prop="contacts">
              <el-input v-model.trim="ruleForm.contacts" placeholder="请输入门店负责人" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model.number="ruleForm.contactPhone" placeholder="请输入联系方式" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店邮箱" prop="email">
              <el-input v-model.trim="ruleForm.email" placeholder="请输入邮箱" @blur="sendEmail" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="margin_top_20">
      <div slot="header" class="clearfix">
        <span>营业信息</span>
      </div>
      <div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="纳税人识别号" prop="taxpayerNo">
              <el-input v-model.trim="ruleForm.taxpayerNo" placeholder="请输入纳税人识别号" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传营业执照" prop="licenseImage">
              <app-uploader title="营业执照" :limit="1" :initFiles="ruleForm.licenseImg" :accept="'image/*'" :file-format="fileFormat" @change="handleImagesOption($event, 'licenseImg')"></app-uploader>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <div class="margin_top_20 text-center">
      <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
      <el-button>取消</el-button>
    </div>
  </el-form>
</template>

<script>
import Setting from '@/settings'
import AppUploader from '@/components/AppUploader/index'
import { provinceMerchabt, addShopMerchabt, streetMerchabt, getMerchantList, reviseShopMerchabt } from '@/api/merchants'
import { myMixin } from '@/layout/mixin/ResizeHandler'
export default {
  mixins: [myMixin],
  components: {
    AppUploader,
  },
  data() {
    //   let checkEmail = (rule, value,callback) =>{//验证邮箱
    //   const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    //   if(value != '' && !regEmail.test(value)) {
    //     callback(new Error('请输入有效的邮箱'));
    //   }
    // }
    return {
      MerchantId: JSON.parse(this.$store.state.user.userInfo).name,
      uploadUrl: `${process.env.VUE_APP_BASE_API}/cloudApi/datacenter/file/uploadFile`, //图片上传地址
      imgBaseUrl: `${process.env.VUE_APP_FILE_URL}/`,
      logoDialog: false, //logao图片弹窗
      storeImgDialog: false, //实景图片弹窗
      licenseDialog: false, //营业执照弹窗
      logoImageUrl: null, //logo弹窗地址
      storeImgUrl: null, //实景图弹窗地址
      licenseUrl: null, //营业执照弹窗地址
      logoList: [], //logo图片地址数组
      storeImgList: [], //实景图数组
      licenseImgList: [], //营业执照数组图
      merchantValue: '', //所属商户绑定的
      selectedItem: {},
      valueId: '', //商户名或id
      provinceData: [], //省数据
      cityData: [], //市数据
      districtData: [], //区的数据
      streetData: [], //街道数据
      value1: false,
      value2: false,
      header: { ContentType: 'multipart/form-data' },
      ruleForm: {
        creatorId: JSON.parse(this.$store.state.user.userInfo).id,
        storeNo: null, //门店编码
        userName: '', //账号
        storeName: '', //店铺名
        storeType: '', //店铺类型
        address: '', //详细地址
        mchId: null,
        storeLogo: '', //门店logo
        storeImg: '', //门店实景图
        contacts: '', //门店联系人
        contactPhone: '', //联系方式
        email: '', //邮箱
        taxpayerNo: '', //纳税人识别号
        licenseImg: '', //营业执照图片
        bindStatus: '', //绑定状态
        isPhysicalStore: '', //是否有实体店 0 没有 1 有
        provinceName: '', //省名称
        cityName: '', //市名称
        districtName: '', //区的名称
        streetName: '', //街道名称
        province: '', //省的ID
        city: '', //市的ID
        district: '', //区的ID
        street: '', //街道ID
        operationTime: '', //操作时间
      },
      shopClass: [
        { value: 1, label: '平台' },
        { value: 2, label: '加盟' },
        { value: 3, label: '自营' },
        { value: 4, label: '联盟' },
        { value: 5, label: '专卖' },
        { value: 6, label: '其他' },
      ],
      merchantName: [], //商户数据
      rules: {
        //表单验证
        userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        storeName: [{ required: true, message: '请输入店铺名', trigger: 'blur' }],
        storeNo: [{ required: true, message: '请输入店铺编码', trigger: 'blur' }],
        storeType: [{ required: true, message: '请选择店铺类型', trigger: 'change' }],
        provinceName: [{ required: true, message: '请选择所在省份', trigger: 'change' }],
        cityName: [{ required: true, message: '请选择所在市', trigger: 'change' }],
        districtName: [{ required: true, message: '请选择所在区', trigger: 'change' }],
        streetName: [{ required: true, message: '请选择所在街道', trigger: 'change' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        logoImage: [{ required: true, message: '请上传门店logo附件' }],
        storeImage: [{ required: true, message: '请上传门店实景图附件' }],
        licenseImage: [{ required: true, message: '请上传营业执照附件' }],
        contacts: [{ required: true, message: '请输入门店负责人', trigger: 'blur' }],
        contactPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '您输入的数字长度有误', trigger: 'blur' },
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        taxpayerNo: [{ required: true, message: '请输入纳税人识别号', trigger: 'blur' }],
        bankcard: {
          bankName: [{ required: true, message: '请输入开户名称', trigger: 'blur' }],
          bankcardNumber: [{ required: true, message: '请输入银行账户', trigger: 'blur' }],
          bankcardType: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
          address: [{ required: true, message: '请输入开户地址', trigger: 'blur' }],
          bankPhone: [{ required: true, message: '请输入开户预留电话', trigger: 'blur' }],
        },
      },
      fileFormat: ['jpg', 'jpeg', 'png'],
    }
  },
  computed: {
    setItem() {
      return this.$route.params.val
    },
  },
  created() {
    if (JSON.parse(this.$store.state.user.userInfo).userType != 0) {
    } else {
      this.rules.mchId = [{ required: true, message: '请选择所属商户', trigger: 'change' }]
    }
    this.provinceMethod()
    this.merchants()
    this.ruleForm.operationTime = this.getNowFormatDate()
    if (this.setItem) {
      this.ruleForm = this.setItem
      this.ruleForm.provinceName = this.setItem.provinceName
      this.ruleForm.cityName = this.setItem.cityName
      this.ruleForm.districtName = this.setItem.districtName
      this.ruleForm.streetName = this.setItem.streetName
      this.ruleForm.address = this.setItem.address
      this.ruleForm.mchId = this.setItem.mchId
      this.valueId = this.setItem.mchName
      let logoObj = { name: 'logo', url: this.imgBaseUrl + this.setItem.storeLogo }
      let storeImgObj = { name: 'store', url: this.imgBaseUrl + this.setItem.storeImg }
      this.logoList.push(logoObj)
      this.storeImgList.push(storeImgObj)
      if (this.setItem.bindStatus == 0) {
        this.value1 = true
      } else {
        this.value1 = false
      }
      this.ruleForm.bindStatus = this.setItem.bindStatus
      this.ruleForm.isPhysicalStore = this.setItem.isPhysicalStore
      if (this.setItem.isPhysicalStore == 1) {
        this.value2 = true
      } else {
        this.value2 = false
      }
      let licenselmgObj = { name: 'licensel', url: this.imgBaseUrl + this.setItem.licenseImg }
      this.licenseImgList.push(licenselmgObj)
      if (this.setItem.licenseImg || this.setItem.storeImg || this.setItem.storeLogo) {
        let { logoImage, ...data } = this.rules.logoImage
        this.rules.logoImage = data
        let { storeImage, ...list } = this.rules.storeImage
        this.rules.storeImage = list
        let { licenseImage, ...res } = this.rules.licenseImage
        this.rules.licenseImage = res
      }
    }
  },
  methods: {
    handleImagesOption(value, key) {
      if (value && value.length) {
        this.ruleForm[key] = value.map(item => item.fileUrl)
      } else {
        this.ruleForm[key] = null
      }
    },
    sendEmail() {
      var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (this.ruleForm.email != '' && !regEmail.test(this.ruleForm.email)) {
        this.$message({ message: '邮箱格式不正确', type: 'error' })
        this.emailForm.email = ''
      }
    },
    async merchants() {
      //获取商户列表
      let res = await getMerchantList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      })
      if (res.code == 200) {
        this.merchantName = res.data.list
      }
    },

    provinceChange(val) {
      //选择省时触发
      this.ruleForm.provinceName = val.name
      this.ruleForm.province = val.id
      this.cityData = val.children
    },
    cityNameChange(val) {
      //选择市时触发
      this.ruleForm.cityName = val.name
      this.ruleForm.city = val.id
      this.districtData = val.children
    },
    async districtChange(val) {
      //选择区的时候触发
      this.ruleForm.districtName = val.name
      this.ruleForm.district = val.id
      let streetRes = await streetMerchabt({ parentId: val.id })
      if (streetRes.code == 200) {
        this.streetData = streetRes.data
      }
      console.log(streetRes)
    },
    streetChange(val) {
      //选择街道时触发
      this.ruleForm.streetName = val.name
      this.ruleForm.street = val.id
    },
    switchChange(val) {
      //绑定门店开关触发
      if (val == true) {
        this.ruleForm.bindStatus = 0
        console.log(this.ruleForm.bindStatus)
      } else {
        this.ruleForm.bindStatus = 1
        console.log(this.ruleForm.bindStatus)
      }
    },
    switchChange2(val) {
      //线上店铺开关触发
      if (val == true) {
        this.ruleForm.isPhysicalStore = 1
      } else {
        this.ruleForm.isPhysicalStore = 0
      }
    },
    async provinceMethod() {
      let res = await provinceMerchabt()
      if (res.code == 200) {
        this.provinceData = res.data
      }
    },
    logoPreview(file) {
      //查看门店logo
      this.logoImageUrl = file.url
      this.logoDialog = true
    },
    handleRemove(file, fileList) {
      //上传门店logo删除
      if (fileList.length == 0) {
        this.rules.logoImage = [{ required: true, message: '请上传门店logo附件', trigger: 'change' }]
      }
    },
    handlePictureCardPreview(res, fileList, val) {
      //上传门店logo成功
      if (res.code == 200) {
        this.$message({ message: '上传成功', type: 'success' })
        this.ruleForm.storeLogo = res.data.fileUrl
        if (val.length == 1) {
          let { logoImage, ...data } = this.rules.logoImage
          this.rules.logoImage = data
        }
        this.$refs.ruleForm.clearValidate('logoImage')
      } else {
        this.$message.error('上传失败')
      }
    },
    storeImgPreview(file) {
      //查看门店实景图
      this.storeImgUrl = file.url
      this.storeImgDialog = true
    },
    RemovebstoreImg(file, fileList) {
      //上传门店实景图删除
      if (fileList.length == 0) {
        this.rules.storeImage = [{ required: true, message: '请上传门店实景图附件', trigger: 'change' }]
      }
    },
    handlestoreImg(res, fileList, val) {
      //上传门店实景图成功
      if (res.code == 200) {
        this.$message({ message: '上传成功', type: 'success' })
        this.ruleForm.storeImg = res.data.fileUrl
        if (val.length == 1) {
          let { storeImage, ...data } = this.rules.storeImage
          this.rules.storeImage = data
        }
        this.$refs.ruleForm.clearValidate('storeImage')
      } else {
        this.$message.error('上传失败')
      }
    },
    licensePreview(file) {
      //查看营业执照
      this.licenseUrl = file.url
      this.licenseDialog = true
    },
    RemoveblicenseImg(file, fileList) {
      //上传营业执照删除
      if (fileList.length == 0) {
        this.rules.licenseImage = [{ required: true, message: '请上传营业执照附件', trigger: 'change' }]
      }
    },
    handlelicenseImg(res, fileList, val) {
      //上传营业执照成功
      if (res.code == 200) {
        this.$message({ message: '上传成功', type: 'success' })
        this.ruleForm.licenseImg = res.data.fileUrl
        if (val.length == 1) {
          let { licenseImage, ...data } = this.rules.licenseImage
          this.rules.licenseImage = data
        }
        this.$refs.ruleForm.clearValidate('licenseImage')
      } else {
        this.$message.error('上传失败')
      }
    },
    submitForm(formName) {
      console.log(1)
      this.$refs[formName].validate(valid => {
        console.log(12)
        if (valid) {
          console.log(123)
          this.addShop()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async addShop() {
      //新增与修改
      if (JSON.parse(this.$store.state.user.userInfo).userType != 0) {
        this.ruleForm.mchId = JSON.parse(this.$store.getters.userInfo).mchId
      }
      if (this.setItem) {
        let reviseRes = await reviseShopMerchabt(this.ruleForm)
        this.$message({ message: '修改成功', type: 'success' })
        this.$router.back()
      } else {
        console.log(this.ruleForm)
        let addshopRes = await addShopMerchabt(this.ruleForm)
        if (addshopRes.code == 200) {
          this.$message({ message: '新增成功', type: 'success' })
          this.$router.back()
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
</style>
